/**  
 * @Title: YcdcTelnet.java
 * @Package org.sera.telnet
 * @Description:
 * @author ICSS
 * @date 2015-5-29 下午3:33:48
 * @version V1.0  
 */
package org.sera.telnet;

import java.io.IOException;

import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.net.telnet.TelnetClient;

/**
 * @ClassName: YcdcTelnet
 * @Description: YcdcTelnet.jar -h 10.1.1.1 [-p 23]
 * @author ICSS
 * @date 2015-5-29 下午3:33:48
 * 
 */
public class YcdcTelnet {

	static TelnetClient tc = null;

	public static void main(String[] args) throws Exception {

		// Create a Parser
		CommandLineParser parser = new BasicParser();
		Options options = new Options();
		options.addOption("H", "help", false, "Print this usage information");
		options.addOption("h", "host", true, "the target host addr.");
		options.addOption("p", "port", true, "the target host port.");
		// Parse the program arguments
		CommandLine commandLine;

		String remoteip = "";
		int remoteport = 0;

		tc = new TelnetClient();

		try {
			commandLine = parser.parse(options, args);
			// Set the appropriate variables based on supplied options
			if (commandLine.hasOption('H')) {
				// automatically generate the help statement
				HelpFormatter formatter = new HelpFormatter();
				formatter.printHelp("YcdcTelnet", options);
				System.exit(0);
			}
			if (commandLine.hasOption('h')) {
				remoteip = commandLine.getOptionValue('h');
			} else {
				System.err.println("Exception: host is not allow null!");
				System.exit(1);
			}
			if (commandLine.hasOption('p')) {
				remoteport = Integer.parseInt(commandLine.getOptionValue('p'));
			} else {
				remoteport = 23;
			}
			System.out.println("try connect to host is [" + remoteip
					+ "],port is [" + remoteport + "]");
			tc.connect(remoteip, remoteport);
			System.out.println("connect successfull!!!");
		} catch (Exception e) {
			System.err.println(e.getMessage());
			System.exit(1);
		} finally {
			try {
				tc.disconnect();
			} catch (IOException e) {
				System.err.println(e.getMessage());
			}
		}
	}

}
